import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class AlterPageService {
    boolean transactional = true

    def fileService
    
    /*def boolean existsPage(page) {
    	def intance = Page.findByNumberPage(page)
    	if (instance) {
    		return  true
    	} else {
    		return false
    	}
    }*/
    
    def add(file, params, user){
    	def instance = new AlterPage(params)
    	instance.createdBy = user
    	fileService.createPath( CH.config.comics.path +"/comic/" + instance.homePage.comic.name + "/pages" )
    	fileService.createPath( CH.config.comics.path +"/comic/" + instance.homePage.comic.name + "/pages/" + instance.homePage.name )
    	def alterPagePath = CH.config.comics.path +"/comic/" + instance.homePage.comic.name + "/pages/" + instance.homePage.name + "/" + instance.name + "numAleatori"
    	println "alterPagePath " +alterPagePath
    	fileService.createPath( alterPagePath )
    	
    	if(!instance.hasErrors()) {
			if(!file.isEmpty()) {
				def validate = fileService.validate(file, CH.config.comics.maxSizeAvatar)
	    		if(validate.ext != null) {
	    			instance.extFile = validate.ext
	    			instance.pathFile = instance.alias
 	    			file.transferTo( new File(alterPagePath+"/"+ instance.path) )
	    		} else {
	    			instance.errors.rejectValue('path',null,validate.error)
	    			return [instance:instance]
	    		}
			} else {
				instance.pathFile = CH.config.comics.defaultPathImageComic.split("\\.")[0]
				instance.extFile = CH.config.comics.defaultPathImageComic.split("\\.")[1]
			}
	    	
	    	if(!instance.hasErrors()) { instance.save() }
    	}
		return [instance:instance]
    }
    
    def update(file, params) {
    	def instance = AlterPage.get(params.id)
    	if (instance) {
            if (params.version) {
                def version = params.version.toLong()
                if (instance.version > version) {
                    instance.errors.rejectValue("version", "alterPage.optimistic.locking.failure", "Another user has updated this AlterPage while you were editing")
                    return instance
                }
            }
            instance.properties = params

            if(file != null && !file.isEmpty()) {
            	def path = CH.config.comics.path +"/page/" +instance.name + "/"	//TODO: corregir 
            	fileService.deleteFile(path, instance.name +"."+instance.imageExt)
            	add (file, params)
            } else {
            	println "no se ha modificado el fichero"
            }
            	
            instance.save()
        	return instance
        }
        else {
        	return null
        }
    }
}
